<template>
  <!-- <div class="no-print">不要打印区域</div> -->
  <div class="print-wrap" :class="{ 'is-submited':status==2||exporting, 'is-exporting':exporting }">
    <!-- 打印的内容 -->
    <div v-if="isShow" class="page-wrap" ref="print">
      <div id="maintenReport">
        <div id="maintenReport1">
          <!-- 封面 -->
          <cover
            :initData="coverData"
            :pronum="pronum"
            :status="status"
            :directoryOrder="directoryOrder"
            ref="coverObj"
            @chooseDirectory="chooseDirectory"
          ></cover>
          <!-- 报告简述 -->
          <briefly
            :initData="brieflyData"
            :proname="proname"
            :pronum="pronum"
            :status="status"
            @changePronum="changePronum"
            ref="brieflyObj"
          ></briefly>
          <!-- 附件一 -->
          <attachment1
            v-show="directory.attachment1"
            :class="{'is-show':directory.attachment1}"
            :initData="attachment_1_Data"
            :proname="proname"
            :pronum="pronum"
            :status="status"
            :directoryOrder="directoryOrder"
            @changePronum="changePronum"
            ref="attachment_1_Obj"
          ></attachment1>
          <!-- 附件二 -->
          <attachment2
            v-show="directory.attachment2"
            :class="{'is-show':directory.attachment2}"
            :initData="attachment_2_Data"
            :proname="proname"
            :pronum="pronum"
            :status="status"
            :directoryOrder="directoryOrder"
            @changePronum="changePronum"
            ref="attachment_2_Obj"
          ></attachment2>
          <!-- 附件三 -->
          <attachment3
            v-show="directory.attachment3"
            :class="{'is-show':directory.attachment3}"
            :initData="attachment_3_Data"
            :proname="proname"
            :pronum="pronum"
            :startTime="startTime"
            :endTime="endTime"
            :status="status"
            :directoryOrder="directoryOrder"
            @changePronum="changePronum"
            ref="attachment_3_Obj"
          ></attachment3>
        </div>
        <div id="maintenReport2">
          <!-- 附件四 -->
          <attachment4
            v-show="directory.attachment4"
            :class="{'is-show':directory.attachment4}"
            :initData="attachment_4_Data"
            :proname="proname"
            :pronum="pronum"
            :startTime="startTime"
            :endTime="endTime"
            :status="status"
            :directoryOrder="directoryOrder"
            @changePronum="changePronum"
            ref="attachment_4_Obj"
          ></attachment4>
          <!-- 附件五 -->
          <attachment5
            v-show="directory.attachment5"
            :class="{'is-show':directory.attachment5}"
            :initData="attachment_5_Data"
            :proname="proname"
            :pronum="pronum"
            :startTime="startTime"
            :endTime="endTime"
            :status="status"
            :directoryOrder="directoryOrder"
            @changePronum="changePronum"
            ref="attachment_5_Obj"
          ></attachment5>
          <!-- 附件六 -->
          <attachment6
            v-show="directory.attachment6"
            :class="{'is-show':directory.attachment6}"
            :initData="attachment_6_Data"
            :proname="proname"
            :pronum="pronum"
            :startTime="startTime"
            :endTime="endTime"
            :status="status"
            :directoryOrder="directoryOrder"
            @changePronum="changePronum"
            ref="attachment_6_Obj"
          ></attachment6>
        </div>
      </div>
    </div>
    <!-- 操作按钮 -->
    <el-row class="verifyidentity-button">
      <el-button @click.stop="closeFun" round>取消</el-button>
      <el-button v-if="status != 2" type="primary" @click="saveReport" round>保存</el-button>
      <el-button v-if="status != 2" type="primary" @click="submitReport" round>提交</el-button>
      <el-button type="primary" @click="printPage" round>打印</el-button>
      <el-button type="primary" @click="exportPdf" round>导出</el-button>
    </el-row>
    <!-- 更换图片弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      title="更换图片"
      width="600px"
      top="15vh"
      v-if="imgDialog"
      :visible.sync="imgDialog"
      @close="closeImgDialog"
      v-dialogDrag
      append-to-body
    >
      <change-pic
        :parames="currentPicInfo"
        :setPrePic="currentSetPrePic"
        :setPostPic="currentSetPostPic"
        :closeFun="closeImgDialog"
      ></change-pic>
    </el-dialog>
    <create-pdf ref="CreatePdf"></create-pdf>
  </div>
</template>
<script>
import './print.css'
import '@/styles/mixin.scss'
import Cover from './Model/Cover'
import Briefly from './Model/Briefly'
import Attachment1 from './Model/Attachment-1'
import Attachment2 from './Model/Attachment-2'
import Attachment3 from './Model/Attachment-3/Main'
import Attachment4 from './Model/Attachment-4/Main'
import Attachment5 from './Model/Attachment-5/Main'
import Attachment6 from './Model/Attachment-6/Main'
import ChangePic from './Dialog/ChangePic'
import { getMaintenanceReportData, save, submit } from '@/api/maintenanceReport'
import CreatePdf from './createPdf'
const orderCHN = ['一', '二', '三', '四', '五', '六']

export default {
  name: 'ReportPrint',
  props: {
    reportId: {
      required: true,
    },
    reportNum: {
      required: true,
    },
    status: {
      required: true,
    },
    closeFun: {
      required: true,
    },
  },
  components: {
    Cover,
    Briefly,
    Attachment1,
    Attachment2,
    Attachment3,
    Attachment4,
    Attachment5,
    Attachment6,
    ChangePic,
    CreatePdf,
  },
  data() {
    return {
      isShow: false,
      serialNumber: this.reportNum,
      coverData: {}, // 封面数据
      brieflyData: {}, // 报告简述数据
      attachment_1_Data: {}, // 附件一数据
      attachment_2_Data: {}, // 附件二数据
      attachment_3_Data: {}, // 附件三数据
      attachment_4_Data: {}, // 附件四数据
      attachment_5_Data: {}, // 附件五数据
      attachment_6_Data: {}, // 附件六数据
      proname: '', // 项目名称
      pronum: '', // 项目编号
      startTime: '', // 开始时间
      endTime: '', // 结束时间
      imgDialog: false, // 更换图片弹框
      currentPicInfo: {}, // 当前更改图片集合的信息
      currentSetPrePic: '',
      currentSetPostPic: '',
      directory: {
        attachment1: true,
        attachment2: true,
        attachment3: true,
        attachment4: true,
        attachment5: true,
        attachment6: true,
      },
      directoryOrder: {
        attachment1: '一',
        attachment2: '二',
        attachment3: '三',
        attachment4: '四',
        attachment5: '五',
        attachment6: '六',
      },
      exporting: false,
    }
  },
  created() {
    let that = this
    // 获取维保报告数据
    getMaintenanceReportData({
      id: that.reportId,
    }).then((res) => {
      // let res = {"status":200,"info":"操作成功","total":139,"data":{"id":"报告id","head":{"owner":"委托单位","writername":"编制/审核人","pronum":"项目编号","period":"维保周期","siteurl":"www.haxf.cn","address":"深圳市龙岗区梅坂大道与雅宝路交汇处星河雅宝创新产业园一期A栋10楼","proname":"项目名称","proaddr":"项目地址","writedate":"2019年06月01日","company":"维保单位","aptitude":"广公消技字[2016]第0009号","phonefax":"0755-85219816/85219817","workers":"作业人员","email":"szhuian119@126.com"},"enclosureFour":{"inspectRecord":[{"systemName":"系统名称","record":[{"assetType":"资产类别","deviceNum":"设备总数","checkedNum":"已查数量","workContentText":["作业子内容1","作业子内容2","作业子内容3"],"record":[{"area":"区域/编号","deviceName":"设备名称","workContent":["内容1结果","内容2结果","内容3结果"]}]}]}],"fireRecord":{"fireSafeUser":"消防安全管理人（签名）","fireSafeDate":"XXXX:XX:XX","inspectName":"巡查人（签名）","inspectDate":"XXXX:XX:XX","remark":"备注","inspectItem":[{"sysName":"系统名称","sysItem":[{"inspectFault":"故障数","inspectRepair":"巡查修复数","inspectResult":"巡查结果","categoryName":"类别名称","inspectContent":"巡查内容"}]}]},"workPic":[{"inspectTaskId":"巡查任务id","inspectPicBeforeUrls":"作业前照片","inspectPicAfterUrls":"作业后照片","inspectTaskName":"巡查任务名称"}]},"enclosureTwo":{"regulatoryAlarm":"监管报警","alarmfire":"火警报警数","alarmnote":"火警情况说明","alarmfake":"误报数","alarmfault":"故障报警数","fixednum":"修复数","unalarm":"漏报"},"enclosureThree":{"fireRecord":[{"createTime":"发现时间","createUser":"发现人员","address":"故障部位","description":"情况描述","systemName":"所属系统","isStopSystem":"0","stopTime":"停用时间","safetyMethod":"安全措施","matainTime":"维修时间","matainUser":"维修人员","matainMethod":"维修方法","isFaultExclude":"1","confirmUser":"确认人","followUser":"跟进人","followDesc":"待跟进事项"}],"workPic":[{"maintainTaskId":"故障id","maintainPicAfterUrls":"作业后照片","maintainPicBeforeUrls":"作业前照片","maintainTaskName":"隐患描述内容XXX"}]},"enclosureOne":{"patrol":[{"total":"计划任务数","completionRate":"完成率","sys":"系统","complete":"完成任务数","remarks":"备注"},{"total":"计划任务数","completionRate":"完成率","sys":"系统","complete":"完成任务数","remarks":"备注"}],"maintain":[{"total":"计划任务数","completionRate":"完成率","sys":"系统","complete":"完成任务数","remarks":"备注"},{"total":"计划任务数","completionRate":"完成率","sys":"系统","complete":"完成任务数","remarks":"备注"}],"test":[{"total":"计划任务数","completionRate":"完成率","sys":"系统","complete":"完成任务数","remarks":"备注"},{"total":"计划任务数","completionRate":"完成率","sys":"系统","complete":"完成任务数","remarks":"备注"}],"repair":[{"total":"计划任务数","completionRate":"完成率","sys":"系统","complete":"完成任务数","remarks":"备注"},{"total":"计划任务数","completionRate":"完成率","sys":"系统","complete":"完成任务数","remarks":"备注"}],"temporary":[{"total":"计划任务数","completionRate":"完成率","sys":"系统","complete":"完成任务数","remarks":"备注"},{"total":"计划任务数","completionRate":"完成率","sys":"系统","complete":"完成任务数","remarks":"备注"}]},"enclosureFive":{"maintainRecords":[{"maintainPicsDetail":[{"maintainPicAfterUrls":"作业后照片","maintainPicBeforeUrls":"作业前照片","maintainTaskName":"保养任务名称1"},{"maintainPicAfterUrls":"作业后照片","maintainPicBeforeUrls":"作业前照片","maintainTaskName":"保养任务名称2"}],"projectName":"项目名称"},{"systemMiantainrecords":[{"followPersonName":"跟进人签名","maintainTime":"保养时间","hours":"总工时","testPersonName":"测试人签名","sysName":"系统名称","remark":"备注","maintainDetai":[{"area":"区域/编号","miantainedCount":" 已保养数量","equpmentCount":"设备总数","itemDetail":[{"itemName":"保养项目","itemSituation":"保养完成情况"}],"equpmentName":"设备名称","assetsCategory":"资产类别"},{"area":"区域/编号","miantainedCount":" 已保养数量","itemDetai":[{"itemName":"保养项目","itemSituation":"保养完成情况"}],"equpmentCount":"设备总数","equpmentName":"设备名称","assetsCategory":"资产类别"}],"maintainDate":"XXXX:XX:XX年月日保养日期"}]}]},"enclosureSix":{"maintainRecords":[{"maintainPicsDetail":[{"maintainPicAfterUrls":"作业后照片","maintainPicBeforeUrls":"作业前照片","maintainTaskName":"测试任务名称1"},{"maintainPicAfterUrls":"作业后照片","maintainPicBeforeUrls":"作业前照片","maintainTaskName":"测试任务名称2"}]},{"testRecordsChart":{"certificateDate":"XXXX:XX:XX年月日","fireResponsiblePersonName":"消防安全责任人或消防安全管理人（签名）","testItem":[{"sysName":"系统名称","sysItem":[{"testFault":"故障数","testContent":"测试内容","testResult":"测试结果","categoryName":"类别名称","testRepair":"测试修复数"}]}],"fireResponsibleDate":"XXXX:XX:XX年月日","leavalCertificateNub":"等级证书编号","testResult":"测试结论","testResultDate":"XXXX年XX月XX日","testName":"测试人（签名）"}},{"testRecordsForm":[{"followPersonName":"跟进人签名","maintainTime":"保养时间","hours":"总工时","testPersonName":"测试人签名","systemName":"系统名称","record":[{"deviceNum":"设备总数","record":[{"area":"区域/编号","workContent1":"作业子内容1","deviceName":"设备名称","workContent3":"作业子内容3","workContent2":"作业子内容2"}],"checkedNum":"已查数量","assetType":"资产类别"}],"remark":"备注","maintainDate":"XXXX:XX:XX年月日保养日期"}]}]},"introduction":{"owner":"委托单位","prohigh":"建筑高度","summary":"简介","period":"项目地址","manager":"项目复杂人","proname":"项目名称","protype":"使用性质","fireSystem":[{"sysId":"消防系统id","flag":"1","system":"消防系统"},{"sysId":"消防系统id","flag":"2","system":"消防系统"}],"proarea":"建筑面积","writedate":"编制日期","profloor":"建筑层数","time":"维保时间","workers":"作业人员"}}}
      if (res.status === 200) {
        let data = JSON.parse(res.data)
        that.coverData = data.head // 封面数据
        that.brieflyData = data.introduction // 报告简述数据
        that.attachment_1_Data = data.enclosureOne // 附件一数据
        that.attachment_2_Data = data.enclosureTwo // 附件二数据
        that.attachment_3_Data = data.enclosureThree // 附件三数据
        that.attachment_4_Data = data.enclosureFour // 附件四数据
        that.attachment_5_Data = data.enclosureFive // 附件五数据
        that.attachment_6_Data = data.enclosureSix // 附件六数据
        that.proname = data.head.proname // 项目名称
        that.pronum = data.head.pronum // 项目编号
        that.startTime = data.head.startTime
        that.endTime = data.head.endTime
        that.isShow = true

        if (typeof data.head.directory !== 'undefined') {
          this.directory = data.head.directory
        }

        if (this.status == 2) {
          this.setDirectoryOrder()
        }

        that.$nextTick(() => {
          $('label.cid').html('报告编号：' + that.serialNumber)
          if (that.status == 2) {
            $('input').attr('readonly', true).attr('disabled', true)
            $('textarea').attr('readonly', true).attr('disabled', true)
          }
          if (typeof data.head.directory !== 'undefined') {
            this.$refs.coverObj.directory = data.head.directory
          }
        })

        document.title = data.head.owner + data.head.period + '维保报告'
      }
    })
  },
  beforeDestroy() {
    document.title = '智慧消防平台'
  },
  methods: {
    getAllData(needChecked) {
      let that = this
      let coverData = that.$refs.coverObj.getData(needChecked) // 封面数据
      let brieflyData = that.$refs.brieflyObj.getData(needChecked) // 报告简述数据
      let attachment_1_Data = that.$refs.attachment_1_Obj.getData() // 附件一数据
      let attachment_2_Data = that.$refs.attachment_2_Obj.getData() // 附件二数据
      let attachment_3_Data = that.$refs.attachment_3_Obj.getData() // 附件三数据
      let attachment_4_Data = that.$refs.attachment_4_Obj.getData() // 附件四数据
      let attachment_5_Data = that.$refs.attachment_5_Obj.getData() // 附件五数据
      let attachment_6_Data = that.$refs.attachment_6_Obj.getData() // 附件六数据
      if (
        coverData &&
        brieflyData &&
        attachment_1_Data &&
        attachment_2_Data &&
        attachment_3_Data &&
        attachment_4_Data &&
        attachment_5_Data &&
        attachment_6_Data
      ) {
        return {
          head: coverData, // 封面数据
          introduction: brieflyData, // 报告简述数据
          enclosureOne: attachment_1_Data, // 附件一数据
          enclosureTwo: attachment_2_Data, // 附件二数据
          enclosureThree: attachment_3_Data, // 附件三数据
          enclosureFour: attachment_4_Data, // 附件四数据
          enclosureFive: attachment_5_Data, // 附件五数据
          enclosureSix: attachment_6_Data, // 附件六数据
        }
      } else {
        return false
      }
    },
    // 保存
    saveReport() {
      let that = this
      let content = that.getAllData(false)

      if (content) {
        save({
          id: that.reportId,
          content: JSON.stringify(content),
        }).then((res) => {
          if (res.status === 200) {
            that.$message({
              type: 'success',
              message: '保存成功!',
            })
          } else {
            that.$message({
              type: 'warning',
              message: '保存失败!',
            })
          }
          that.closeFun()
        })
      }
    },
    // 提交
    submitReport() {
      let that = this
      let content = that.getAllData(true)

      if (content) {
        submit({
          id: that.reportId,
          content: JSON.stringify(content),
        }).then((res) => {
          if (res.status === 200) {
            that.$message({
              type: 'success',
              message: '提交成功!',
            })
            // 刷新列表
            that.closeFun(true)
          } else {
            that.$message({
              type: 'warning',
              message: '提交失败!',
            })
            that.closeFun()
          }
        })
      }
    },
    // 打印
    printPage() {
      // this.$print(this.$refs.print)
      let that = this
      let coverData = that.$refs.coverObj.getData(true) // 封面数据
      if (coverData) {
        let brieflyData = that.$refs.brieflyObj.getData(true) // 报告简述数据
        if (brieflyData) {
          this.$print(this.$refs.print)
        }
      }
    },
    // 导出pdf
    exportPdf() {
      const loading = this.$loading({
        lock: true,
        text: 'pdf生成中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      this.exporting = true
      if (this.status != 2) {
        this.setDirectoryOrder()
      }
      this.$nextTick(() => {
        // this.getPdf('maintenReport', this.proname, 300, false, (flag, errInfo) => {
        //   loading.close();
        //   if(flag) {
        //     this.$message({
        //       message: 'PDF导出成功！',
        //       type: 'success'
        //     })
        //   } else {
        //     this.$message({
        //       message: '报告过长，PDF导出失败！',
        //       type: 'warning'
        //     })
        //   }
        //   this.exporting=false
        //   if(this.status!=2){
        //     this.setDirectoryOrderDefault()
        //   }
        // })

        this.$refs.CreatePdf.create(
          this.proname,
          'maintenReport',
          (flag, errInfo) => {
            loading.close()
            if (flag) {
              this.$message({
                message: 'PDF导出成功！',
                type: 'success',
              })
            } else {
              this.$message({
                message: '报告过长，PDF导出失败！',
                type: 'warning',
              })
            }
            this.exporting = false
            if (this.status != 2) {
              this.setDirectoryOrderDefault()
            }
          }
        )
      })
    },
    // 修改了项目编号
    changePronum(val) {
      if (val) {
        this.pronum = val
      }
    },
    // 打开更换图片弹框
    openImgDialog(parames, setPrePic, setPostPic) {
      this.currentPicInfo = parames || {}
      // 设置作业前照片方法
      this.currentSetPrePic = setPrePic
      // 设置作业后照片方法
      this.currentSetPostPic = setPostPic
      this.imgDialog = true
    },
    // 关闭更换图片弹框
    closeImgDialog() {
      this.imgDialog = false
    },
    chooseDirectory(dir) {
      this.directory = dir
    },
    setDirectoryOrder() {
      let count = 0
      for (var k in this.directoryOrder) {
        if (this.directory[k]) {
          this.directoryOrder[k] = orderCHN[count]
          count++
        }
      }
    },
    setDirectoryOrderDefault() {
      let count = 0
      for (var k in this.directoryOrder) {
        this.directoryOrder[k] = orderCHN[count]
        count++
      }
    },
  },
}
</script>
<style lang="scss">
@import '~@/styles/print.scss';
</style>
